package com.sddr.config.nacos.operation;

import com.sddr.base.frame.metadata.MetaDataOperation;
import com.sddr.common.nacos.api.NacosApi;
import com.sddr.common.nacos.api.NacosListener;
import com.sddr.config.observe.ConfigNotify;
import com.sddr.config.operation.AbstractRemoteConfigRuleOperation;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author 山顶洞人郑某
 * @className NacosMetaDataOperation.java nacos规则操作
 * @date 2025 07 13
 */
@Slf4j
public class NacosRemoteConfigRuleOperation extends AbstractRemoteConfigRuleOperation {

    private final ExecutorService threadPool = new ThreadPoolExecutor(
            Runtime.getRuntime().availableProcessors()+1, //线程池核心线程数
            Runtime.getRuntime().availableProcessors()*2, //线程池最大线程数
            30, //线程池非核心线程空闲时间
            TimeUnit.SECONDS,//时间单位
            new ArrayBlockingQueue<>(50),//线程池核心线程满后的阻塞队列
            new ThreadPoolExecutor.AbortPolicy() //线程池拒绝策略 默认策略，当线程池和队列都满时，直接抛出
    );

    private final NacosApi nacosApi;

    /**
     * 构造方法
     * @param  nacosApi nacos的操作Api
     * @param metaDataOperation 元数据操作Api
     */
    public NacosRemoteConfigRuleOperation(NacosApi nacosApi,
                                          final MetaDataOperation metaDataOperation,
                                          ConfigNotify configNotify) {
        super(metaDataOperation,configNotify);
        this.nacosApi = nacosApi;
    }
    /**
     * 获取配置信息
     *
     * @param group  组
     * @param dataId 数据Id
     * @return 配置信息
     */
    @Override
    public String getDefiniteConfig(String group, String dataId) throws Exception {
        return nacosApi.getConfig(dataId, group);
    }

    /**
     * 监听配置信息
     */
    @Override
    public void linstenConfig() {
        //获取naocs中是哪个组
        String group = getGroup();
        //获取服务自己的dataId
        String dataId = getDataId(false);
        //获取全局的dataId
        String generaldataId = getDataId(true);
        try
        {
            //监听自己的配置信息
            nacosApi.listenConfig(dataId, group, threadPool, new NacosListener() {
                @Override
                public void callBack(String config) {
                    this.callBack(config);
                }
            });
            //监听全局的配置信息
            nacosApi.listenConfig(generaldataId,group,threadPool,(this::callbackConfig));
        } catch (Exception e ){
            log.error("监听配置信息失败", e);
        }
    }
}
